package com.xxtx.trade.thread;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;

import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.xxtx.trade.agent.dto.ImeiToPhoneDto;
import com.xxtx.trade.agent.mapper.TradeSysAgentMapper;
import com.xxtx.trade.common.enums.ExportEnum;
import com.xxtx.trade.common.util.ExcelUtils;
import com.xxtx.trade.common.util.SpringUserContext;
import com.xxtx.trade.common.util.cache.CacheManager;
import com.xxtx.trade.common.util.model.PageInfo;
import com.xxtx.trade.common.util.model.Result;
import com.xxtx.trade.common.util.springUtil.SpringUtil;
import com.xxtx.trade.fieldManage.dto.FieldManageDto;
import com.xxtx.trade.fieldManage.mapper.FieldManageMapper;
import com.xxtx.trade.sysUser.bean.UrlInfos;
import com.xxtx.trade.sysUser.dto.TradeSysRoleDto;
import com.xxtx.trade.sysUser.dto.TradeSysUserDto;
import com.xxtx.trade.sysUser.vo.TradeSysUserVo;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 代理商统计
 */
@Component
public class DownloadAdminSimThread implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(DownloadAdminSimThread.class);
    private TradeSysRoleDto tradeSysRoleDto;

    private int count;
    private String url;
    private String id; // 每次下载时随机出的 id

    private String userId; // 用户id
    private String agentId; // 这个可以用来在info表中查询

    private String role_id; // 用户角色，管理员与普通用户
    private int type; //1


    /**
     * wzyk修改：excel下载
     */
    @Override
    public void run() {

        Integer pageCount = count / 100000 + 1;
        TradeSysAgentMapper tradeSysAgentMapper = SpringUtil.getBean(TradeSysAgentMapper.class);
        CacheManager cacheManager = SpringUtil.getBean(CacheManager.class);
        FieldManageMapper fieldManageMapper = SpringUtil.getBean(FieldManageMapper.class);

        // 一次性把 imei 和 phone 对照表查询出来，不用查询那么多次
        List<ImeiToPhoneDto> imeiToPhoneDtos = tradeSysAgentMapper.selectImeiList();
        HashMap<String, String> map = new HashMap<>();
        for (ImeiToPhoneDto imeiToPhoneDto : imeiToPhoneDtos) {
            map.put(imeiToPhoneDto.getImei(), imeiToPhoneDto.getPhone());
        }

        Map<String, Object> hashMap = new HashMap<>();

        Workbook workbook = null;

        ExportParams params = new ExportParams();
        try {
            if (type == 1) {
                List<UrlInfos> users = null;
//         查询测试 页数  每次查询10w条数据
                for (int i = 1; i <= pageCount; i++) {

                    tradeSysRoleDto.setPageNo((i - 1) * 100000);
                    if (i == pageCount) {
                        tradeSysRoleDto.setPerPageNum(count % 100000);
                    } else {
                        tradeSysRoleDto.setPerPageNum(100000);
                    }

//                    // 按用户权限查询
                    tradeSysRoleDto.setAgentId(this.agentId);

                    users = tradeSysAgentMapper.selectExcelUrlInfos(tradeSysRoleDto);

                    for (UrlInfos info : users) {
                        // 给users插入phone字段，注意这里是每得到一个info，便搜索它imei对应的phone

                        String phone = map.get(info.getImei());
//                        ImeiToPhoneDto ele = tradeSysAgentMapper.selectImei(info.getImei());
                        if (phone != null) {
                            info.setPhone(phone);
                            Collection<Object> phone_list = new ArrayList<>();
                            phone_list.add(phone.substring(0, 7));
                            String aa = (String) cacheManager.hMGet("phoneOwnership2", phone_list).get(0);
                            if (aa == null){
                                info.setPlace("未入库地区");
                            }else {
                                info.setPlace(aa.split("_")[1]);
                            }
                        } else {
                            info.setPhone("*");
                            info.setPlace("");
                        }
                        // 如果没设置imei可见，那么imei导出时将不显示
                        if (!tradeSysRoleDto.getUser_role().equals("2")) {
                            if (tradeSysRoleDto.getImei_status().equals("0")) info.setImei("");
                        }
                    }

                    if (tradeSysRoleDto.getUser_role().equals("2")) {
                        //通过 EasyPoi 的大数据导出方法 导出
//                        workbook = ExcelExportUtil.exportBigExcel(params, UrlInfos.class, users);
                        workbook = ExcelExportUtil.exportBigExcel(params, UrlInfos.class, users);
                        users.clear();
                    } else {
                        // 生成要导出的数据
                        List<Map<String, String>> resultList = new ArrayList<>();
                        // 生成导出的列名
                        List<ExcelExportEntity> entityList = new ArrayList<>();

                        ExcelExportEntity agentNameEntity = new ExcelExportEntity("客户名称", "agentName");
//                        ExcelExportEntity urlNameEntity = new ExcelExportEntity("链接名称", "urlName");
//                        ExcelExportEntity phoneEntity = new ExcelExportEntity("phone", "phone");
                        entityList.add(agentNameEntity);
//                        entityList.add(urlNameEntity);
//                        entityList.add(phoneEntity);


                        // 查询 可显示 字段，创建列名
                        List<FieldManageDto> fieldManageDtos = fieldManageMapper.getList();
                        for (FieldManageDto fieldManageDto : fieldManageDtos) {
                            if (fieldManageDto.getStatus().equals("1")) {
                                if (fieldManageDto.getSource().equals("1")) {
                                    ExcelExportEntity ele = new ExcelExportEntity(fieldManageDto.getName(), fieldManageDto.getName());
                                    entityList.add(ele);
                                }
                            }
                        }
                        // 装载数据
                        for (UrlInfos urlInfos : users) {
                            Map<String, String> rowMap = new HashMap<>();
                            for (ExcelExportEntity excelExportEntity : entityList) {
                                if (excelExportEntity.getKey().equals("agentName")) {
                                    rowMap.put("agentName", urlInfos.getAgentName());
                                }
                                if (excelExportEntity.getKey().equals("urlName")) {
                                    rowMap.put("urlName", urlInfos.getUrlName());
                                }
                                if (excelExportEntity.getKey().equals("imei")) {
                                    rowMap.put("imei", urlInfos.getImei());
                                }
                                if (excelExportEntity.getKey().equals("idfa")) {
                                    rowMap.put("idfa", urlInfos.getIdfa());
                                }
                                if (excelExportEntity.getKey().equals("oaid")) {
                                    rowMap.put("oaid", urlInfos.getOaid());
                                }
                                if (excelExportEntity.getKey().equals("oaid_md5")) {
                                    rowMap.put("oaidMd5", urlInfos.getOaidMd5());
                                }
                                if (excelExportEntity.getKey().equals("campaign_name")) {
                                    rowMap.put("campaign_name", urlInfos.getCampaignName());
                                }
                                if (excelExportEntity.getKey().equals("createTime")) {
                                    rowMap.put("createTime", urlInfos.getCreateTime());
                                }
                                if (excelExportEntity.getKey().equals("userPhone")) {
                                    rowMap.put("userPhone", urlInfos.getPhone());
                                }
                                if (excelExportEntity.getKey().equals("place")) {
                                    rowMap.put("place", urlInfos.getPlace());
//                                    Collection<Object> phone = new ArrayList<>();
////                                    LOGGER.info(urlInfos.getPhone().substring(0, 7));
//                                    phone.add(urlInfos.getPhone().substring(0, 7));
//                                    List<Object> info_list = cacheManager.hMGet("phoneOwnership2", phone);
//                                    String info = (String) info_list.get(0);
//                                    if (info != null){
//                                        String place = info.split("_")[1];
//                                        rowMap.put("place", place);
//                                    }else {
//                                        rowMap.put("place", "未入库地区");
//                                    }
                                }
                            }
                            resultList.add(rowMap);
                        }
                        workbook = ExcelExportUtil.exportBigExcel(params, entityList, resultList);
                        resultList.clear();
                        users.clear();
                    }
                }  // 分页写入workbook结束
                map.clear();
            }
//            workbook.write(new FileOutputStream("E:/download/" + url));
            workbook.write(new FileOutputStream("/root/develop/export/" + url));

            workbook.close();
            hashMap.put("state", ExportEnum.SUCCESS.getCode());

        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.debug("导出失败信息为" + e.getMessage());
            LOGGER.debug("导出失败信息为" + e.getLocalizedMessage());
            hashMap.put("state", ExportEnum.FAIL.getCode());
        }
        hashMap.put("id", id);
        Date date = new Date();
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
        String LgTime = sdformat.format(date);
        hashMap.put("endTime", LgTime);
        tradeSysAgentMapper.updateExporeByid(hashMap);
    }


    /**
     * 原始导出excel方式
     */
//    @Override
//    public void run() {
//        Integer pageCount = count / 100000 + 1;
//        TradeSysAgentMapper tradeSysAgentMapper = SpringUtil.getBean(TradeSysAgentMapper.class);
//
//        Map<String, Object> hashMap = new HashMap<>();
//        Workbook workbook = null;
//        ExportParams params = new ExportParams();
//        try {
//            if (type==1){
//                List<UrlInfos> users = null;
////         查询测试 页数  每次查询20w条数据
//                for (int i = 1; i <= pageCount; i++) {
//                    tradeSysRoleDto.setPageNo(i);
//                    tradeSysRoleDto.setPerPageNum(100000);
//                    users=tradeSysAgentMapper.selectExcelUrlInfos(tradeSysRoleDto);
//////             通过 EasyPoi 的大数据导出方法 导出
//                    workbook = ExcelExportUtil.exportBigExcel(params, UrlInfos.class, users);
//                    users.clear();
//                }
//            }
////            workbook.write(new FileOutputStream("/root/develop/export/"+url));
//              workbook.write(new FileOutputStream("E:/download/"+url));
//            hashMap.put("state", ExportEnum.SUCCESS.getCode());
//        } catch (IOException e) {
//            e.printStackTrace();
//            LOGGER.debug("导出失败信息为"+e.getMessage());
//            LOGGER.debug("导出失败信息为"+e.getLocalizedMessage());
//            hashMap.put("state", ExportEnum.FAIL.getCode());
//        }
//        hashMap.put("id",id);
//        hashMap.put("endTime",new Date());
//        tradeSysAgentMapper.updateExporeByid(hashMap);
//    }
    public TradeSysRoleDto getTradeSysRoleDto() {
        return tradeSysRoleDto;
    }

    public void setTradeSysRoleDto(TradeSysRoleDto tradeSysRoleDto) {
        this.tradeSysRoleDto = tradeSysRoleDto;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getAgentId() {
        return agentId;
    }

    public void setAgentId(String agentId) {
        this.agentId = agentId;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserId() {
        return this.userId;
    }
}
